package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Service
public class ReportServicelml implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 根据时间区间统计营业额
     *
     * @param begin
     * @param end
     * @return
     */

    @Override
    public TurnoverReportVO report(LocalDate begin, LocalDate end) {

        ArrayList<String> datelist = new ArrayList<>();
        while (!begin.isAfter(end)) {
            datelist.add(begin.toString());
            begin = begin.plusDays(1);
        }
        ArrayList<String> sumamount = new ArrayList<>();
        for (String date : datelist) {
            //获取一天开始的时间
            LocalDateTime localDateTimebegin = LocalDateTime.of(LocalDate.parse(date), LocalTime.MIN);
            //获取一天结束的时间
            LocalDateTime localDateTimeend = LocalDateTime.of(LocalDate.parse(date), LocalTime.MAX);
            Double amount = reportMapper.sumamount(localDateTimebegin, localDateTimeend, Orders.COMPLETED);
            String amountStr = (amount != null) ? amount.toString() : "0.0";
            sumamount.add(amountStr);
        }
        //以逗号分隔
        TurnoverReportVO reportVO = TurnoverReportVO.builder()
                .turnoverList(String.join(",", sumamount))
                .dateList(String.join(",", datelist))
                .build();
        return reportVO;
    }

    @Override
    public OrderReportVO vaildorder(LocalDate begin, LocalDate end) {
        ArrayList<String> datelist = new ArrayList<>();
        while (!begin.isAfter(end)) {
            datelist.add(begin.toString());
            begin = begin.plusDays(1);
        }
        ArrayList<String> sumamount = new ArrayList<>();
        ArrayList<String> orderCountList = new ArrayList<>();
        ArrayList<String> validOrderCountList = new ArrayList<>();
        for (String date : datelist) {
            //获取一天开始的时间
            LocalDateTime localDateTimebegin = LocalDateTime.of(LocalDate.parse(date), LocalTime.MIN);
            //获取一天结束的时间
            LocalDateTime localDateTimeend = LocalDateTime.of(LocalDate.parse(date), LocalTime.MAX);

            //查询每日订单数
            Integer ordercounteveryday = reportMapper.ordernumbyerverday(localDateTimebegin, localDateTimeend, null);
            String orderCountStr = (ordercounteveryday != null) ? ordercounteveryday.toString() : "0";
            orderCountList.add(orderCountStr);
            //查询每日有效订单数

            Integer vaildordernumbyerverday = reportMapper.ordernumbyerverday(localDateTimebegin, localDateTimeend, Orders.COMPLETED);
            String vaildordStr = (vaildordernumbyerverday != null) ? vaildordernumbyerverday.toString() : "0";
            validOrderCountList.add(vaildordStr);
        }
        //查询订单总数
        Integer countorder = reportMapper.countorder(null);
        //查询有效订单数
        Integer vaildcountorder = reportMapper.countorder(Orders.COMPLETED);
        //计算订单完成率
        Double orderCompletionRate = (double) (vaildcountorder / countorder);
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(String.join(",", datelist))
                .orderCountList(String.join(",", orderCountList))
                .validOrderCountList(String.join(",", validOrderCountList))
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime start = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime ending = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> saleslist = reportMapper.gettop10(start, ending, Orders.COMPLETED);
        log.info("saleslist is {}", saleslist);
        String namelist = String.join(",", saleslist.stream().map(s -> s.getName()).collect(Collectors.toList()));
        String numberlist = String.join(",", saleslist.stream().map(s -> String.valueOf(s.getNumber())).collect(Collectors.toList()));
        SalesTop10ReportVO SalesTop10 = SalesTop10ReportVO.builder()
                .nameList(namelist)
                .numberList(numberlist)
                .build();
        return SalesTop10;
    }

    @Override
    public void export(HttpServletResponse response) {
        // 设置响应头信息
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//设置响应体类型为excel
        response.setHeader("Content-Disposition", "attachment; filename=report.xlsx");//以附件的形式下载
        //查询数据提供给模板文件
        LocalDateTime begin = LocalDateTime.now().minusDays(30);//30天之间
        LocalDateTime end = LocalDateTime.now().minusDays(1);//如果不减1天就是31天
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);
        //读取模板文件
        InputStream in = getClass().getClassLoader().getResourceAsStream("template/xlsxtemplate.xlsx");
        try {
            //写入时间
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet1 = excel.getSheet("sheet1");//获取页
            XSSFRow row = sheet1.getRow(1);//获取行
            XSSFCell cell = row.getCell(6);//获取列
            cell.setCellValue("时间:" + begin + "-" + end);//写入时间
            XSSFRow row1 = sheet1.getRow(3);
            //写入概览数据
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            //写入明细数据
            for (int i = 0; i < 30; i++) {  //当天的时间
                LocalDateTime begin1 = begin.plusDays(i);
                LocalDateTime start = begin1.with(LocalTime.MIN);
                LocalDateTime ending = begin1.with(LocalTime.MAX);
                //获取当天时间的营业数据
                BusinessDataVO businessData1 = workspaceService.getBusinessData(start, ending);
                //行数
                XSSFRow row2 = sheet1.getRow(7 + i);
                //日期
                XSSFCell cell1 = row2.getCell(1);
                cell1.setCellValue(begin1 + "");
                //营业额
                XSSFCell cell2 = row2.getCell(2);
                cell2.setCellValue(businessData1.getTurnover());
                //有效订单
                XSSFCell cell3 = row2.getCell(3);
                cell3.setCellValue(businessData1.getValidOrderCount());
                //订单完成率
                XSSFCell cell4 = row2.getCell(4);
                cell4.setCellValue(businessData1.getOrderCompletionRate());
                //平均客单价
                XSSFCell cell5 = row2.getCell(5);
                cell5.setCellValue(businessData1.getUnitPrice());
                //新增用户数
                XSSFCell cell6 = row2.getCell(6);
                cell6.setCellValue(businessData1.getNewUsers());
            }
            //写入客户端
            ServletOutputStream os = response.getOutputStream();
            excel.write(os);
            //关闭资源
            excel.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("运行异常");
        }
    }
}
